# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE, STDOUT
import StringIO
from os import path, sep
import logging
import re
import time

from twisted.internet import reactor

# Files Constants
ROOT_DIR = path.abspath(path.dirname(__file__))
PARENT_DIR = sep.join(ROOT_DIR.split(sep)[:-1])
DOWNLOADED_DIR = path.join(ROOT_DIR, 'downloaded_zip')
WIDGETS_DIR_REL = path.join(ROOT_DIR, 'unzipfiles')

log = logging.getLogger("AlicanteHomebox")

class FluteReceiver:
    def __init__(self, filemanager, timemanager):
        self.filemanager = filemanager
        self.timemanager = timemanager
        self.tomatch = re.compile(r"\File received: file:///(?P<filename>\S+) \(TOI\=[0-9]+\b")
        self.fluteprocesses = {}
        self.doneMapping = False
        self.timemanager.fluteManager = self
        
    def shouldListen(self, fluteip, fluteport):
        #fluteip = "127.0.0.1" # Testing purpose
        
        if not self.fluteprocesses.has_key( (fluteip, fluteport) ):
            reactor.callInThread( self.newConnection, fluteip, fluteport )
            
    def shouldNotListen(self, fluteip, fluteport):
        #fluteip = "127.0.0.1" # Testing purpose
        if self.fluteprocesses.has_key( (fluteip, fluteport) ):
            self.fluteprocesses[ (fluteip, fluteport) ].terminate()
            del(self.fluteprocesses[ (fluteip, fluteport) ])
            log.debug("Nobody watching fluteip: %s and fluteport: %d, should stop listening" % (fluteip, fluteport))
            
        
    def newConnection(self, multicastAddress, port):
        # File received: file:///filetesting.zip (TOI=1)
        # File received: file:///france.zip (TOI=1)
        #newProcess = Popen(["./libs/flute", "-m:%s" % multicastAddress, "-p:%d" % port, "-B:%s" % DOWNLOADED_DIR, "-A"], stdout=PIPE, stderr=STDOUT)
        
        log.debug("New Connection %s, %d" % (multicastAddress, port))
        self.fluteprocesses[ (multicastAddress, port) ] = None
        
        #newProcess = Popen(["telnet", str(multicastAddress), str(port)], stdout=PIPE, stderr=STDOUT)
        newProcess = Popen(["./libs/flute", "-m:%s" % multicastAddress, "-p:%d" % port, "-B:%s" % DOWNLOADED_DIR, "-A"], stdout=PIPE, stderr=STDOUT)
        self.fluteprocesses[ (multicastAddress, port) ] = newProcess
        
        while True:
            result = newProcess.stdout.readline()
            if result == "q":
                break
            if not result:
                break
            regex = self.tomatch.search(result)
            if regex:
                filename = regex.groupdict()['filename']
                self.receivedFile( "%s/%s" % (DOWNLOADED_DIR, filename) )

        
    def killClients(self):
        for client in self.fluteprocesses.itervalues():
            try:
                client.terminate()
            except:
                log.error("Unable to kill flute client")
        
    #def start(self):
        #self.fluteprocess = Popen(["./libs/flute", "-m:224.0.0.2", "-p:5000", "-B:flutedownload2", "-A"], stdout=PIPE)
        #self.process()

    #def process(self):
        #log.debug("Flute Receiver running")
        #while True:
            #result = self.fluteprocess.stdout.readline()
            #if not result:
                #break
            #regex = self.tomatch.search(result)
            #if regex:
                #filename = regex.groupdict()['filename']
                #self.receivedFile("flutedownload2/%s" % filename)
  
    def reactorTest(self, filename):
        import random
        
        if filename == "downloaded_zip/survey2.zip":
            timeToCall = 20
        else:
            timeToCall = random.randint(1, 3)
        reactor.callLater(timeToCall, self.receivedFile, filename)
  
    def receivedFile(self,filename):
        log.debug("Received File: %s" % filename)
        if filename.endswith('.xml'): # Mapping file
            try:
                mappingInfos = self.filemanager.mappingFileParsing(path.join(ROOT_DIR, filename))
            except:
                log.error("Can't load mapping file")
            else:
                self.timemanager.addMappingInfo(mappingInfos)
                self.doneMapping = True
                
        else: # Widget
            try:
                xmlFile = self.filemanager.unzipXml( path.join(ROOT_DIR, filename) )
            except IOError,e:
                log.error( "Error with: %s : %s" % (path.join(ROOT_DIR, filename), e) )
            else:
                newEvent = self.filemanager.xmlParsing(xmlFile, path.join(ROOT_DIR, filename))
                self.timemanager.addToTMD(newEvent)
